import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import { useMenuStore } from '@/store/modules/menu'

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比,
})

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'main',
    children: [
      {
        path: '/login',
        meta: {
          title: '登录',
        },
        component: () => import('@/layout/login.vue'),
      },
      {
        path: '/:catchAll(.*)',
        meta: {
          title: '页面不存在',
        },
        component: () => import('@/layout/404.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  NProgress.start()

  const { setMenuList, menuList, fistMenu } = useMenuStore()

  // 目前对于路由的处理方式是将所有动态路由均放置在layout路由下
  const routes = router.getRoutes()
  const isInitRoutes = !routes.some((item: any) => item.name === 'layout')

  // 页面刷新
  if (isInitRoutes && to.path !== '/login') {
    // 如果未获得菜单列表,则跳转到登录页
    if (!menuList || !menuList.length) {
      next({ path: '/login', replace: true })
      return
    }
    // 已获得菜单列表,则将菜单列表添加到路由中
    setMenuList()

    // 重定向到首页
    if (to.path === '/') {
      next({ path: fistMenu, replace: true })
      return
    }

    // 重新跳转到目标路由
    next({ ...to, replace: true })
    return
  }

  // 设置页面标题
  document.title = to.meta.title as string
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
